<template>
  <div class="main-container">
    <div class="header">
      <div style="display: flex; align-items: center;">
        <el-icon size="24" style="margin-right: 10px;"><Monitor /></el-icon>
        <h2>设备管理系统</h2>
      </div>
      <div style="display: flex; align-items: center;">
        <span style="margin-right: 15px;">欢迎，{{ username }}</span>
        <el-button type="text" @click="handleLogout" style="color: white;">
          <el-icon><SwitchButton /></el-icon>
          退出登录
        </el-button>
      </div>
    </div>
    
    <div class="content">
      <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
        <h3>参数设置 - IMEI:{{ deviceImei }}</h3>
        <el-button @click="$router.push('/devices')">
          <el-icon><ArrowLeft /></el-icon>
          返回列表
        </el-button>
      </div>
      
      <el-tabs v-model="activeTab" type="card">
        <!-- 串口参数 -->
        <el-tab-pane label="串口参数" name="serial">
          <el-card>
            <el-form :model="serialConfig" label-width="150px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="波特率">
                    <el-select v-model="serialConfig.baudRate">
                      <el-option label="1200" :value="1200" />
                      <el-option label="2400" :value="2400" />
                      <el-option label="4800" :value="4800" />
                      <el-option label="9600" :value="9600" />
                      <el-option label="19200" :value="19200" />
                      <el-option label="38400" :value="38400" />
                      <el-option label="57600" :value="57600" />
                      <el-option label="115200" :value="115200" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="数据位">
                    <el-select v-model="serialConfig.dataBits">
                      <el-option label="5" :value="5" />
                      <el-option label="6" :value="6" />
                      <el-option label="7" :value="7" />
                      <el-option label="8" :value="8" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="校验位">
                    <el-select v-model="serialConfig.parity">
                      <el-option label="无校验" value="0" />
                      <el-option label="奇校验" value="1" />
                      <el-option label="偶校验" value="2" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="停止位">
                    <el-select v-model="serialConfig.stopBits">
                      <el-option label="1" :value="1" />
                      <el-option label="2" :value="2" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-card>
        </el-tab-pane>
        
        <!-- 自动轮询 -->
        <el-tab-pane label="自动轮询" name="polling">
          <el-card>
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
              <h4>二级设备列表</h4>
              <div>
                <el-button type="primary" @click="handleAddSubDevice">
                  <el-icon><Plus /></el-icon>
                  添加二级设备
                </el-button>
                <el-button type="danger" @click="handleBatchDeleteSubDevices" :disabled="selectedSubDevices.length === 0">
                  <el-icon><Delete /></el-icon>
                  批量删除
                </el-button>
              </div>
            </div>
            <el-table :data="subDevices" border stripe v-loading="subDeviceLoading" @selection-change="handleSubDeviceSelectionChange">
              <el-table-column type="selection" width="55" />
              <el-table-column prop="subDeviceId" label="二级设备ID" />
              <el-table-column prop="deviceModel" label="设备型号" />
              <el-table-column prop="responseTimeout" label="轮询应答超时时间(ms)" />
              <el-table-column prop="pollingInterval" label="轮询周期时间(ms)" />
              <el-table-column prop="createdTime" label="创建时间">
                <template #default="scope">
                  {{ formatTime(scope.row.createdTime) }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="300">
                <template #default="scope">
                  <el-button type="success" size="small" @click="viewKeys(scope.row)">
                    <el-icon><Document /></el-icon>
                    Modbus配置
                  </el-button>
                  <el-button type="warning" size="small" @click="editSubDevice(scope.row)">
                    <el-icon><Edit /></el-icon>
                    编辑
                  </el-button>
                  <el-button type="danger" size="small" @click="deleteSubDevice(scope.row)">
                    <el-icon><Delete /></el-icon>
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-tab-pane>
        
        <!-- 网络参数 -->
        <el-tab-pane label="网络参数" name="network">
          <el-card>
            <el-form :model="networkConfig" label-width="150px">
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="绑定通讯串口">
                    <el-select v-model="networkConfig.boundSerialPort">
                      <el-option label="RS485" value="RS485" />
                      <el-option label="RS232" value="RS232" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="心跳包发送间隔时间(秒)">
                    <el-input-number v-model="networkConfig.heartbeatInterval" :min="10" :max="3600" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="服务器地址">
                    <el-input v-model="networkConfig.serverAddress" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="服务器端口">
                    <el-input-number v-model="networkConfig.serverPort" :min="1" :max="65535" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="登录客户端ID">
                    <el-input v-model="networkConfig.clientId" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="登录用户名">
                    <el-input v-model="networkConfig.username" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="登录密码">
                    <el-input v-model="networkConfig.password" type="password" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="订阅QOS">
                    <el-select v-model="networkConfig.subscribeQos">
                      <el-option label="0" :value="0" />
                      <el-option label="1" :value="1" />
                      <el-option label="2" :value="2" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="发布QOS">
                    <el-select v-model="networkConfig.publishQos">
                      <el-option label="0" :value="0" />
                      <el-option label="1" :value="1" />
                      <el-option label="2" :value="2" />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="订阅消息主题">
                    <el-input v-model="networkConfig.subscribeTopic" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item label="发布消息主题">
                    <el-input v-model="networkConfig.publishTopic" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
          </el-card>
        </el-tab-pane>
      </el-tabs>
      
      <div style="text-align: center; margin-top: 20px;">
        <el-button type="primary" @click="handleSave" :loading="loading">
          保存配置
        </el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'DeviceConfig',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const loading = ref(false)
    const username = ref(sessionStorage.getItem('username') || '')
    const deviceImei = ref(route.params.imei)
    const activeTab = ref('serial')
    const subDevices = ref([])
    const subDeviceLoading = ref(false)
    const selectedSubDevices = ref([])
    
    const serialConfig = reactive({
      baudRate: 9600,
      dataBits: 8,
      parity: '无校验',
      stopBits: 1
    })
    
    const networkConfig = reactive({
      boundSerialPort: 'RS485',
      heartbeatInterval: 60,
      serverAddress: '139.159.146.106',
      serverPort: 1883,
      clientId: deviceImei.value,
      username: '',
      password: '',
      subscribeQos: 0,
      publishQos: 0,
      subscribeTopic: '',
      publishTopic: ''
    })

    const loadConfigs = async () => {
      try {
        loading.value = true
        const token = sessionStorage.getItem('token')
        const headers = { Authorization: `Bearer ${token}` }
        
        // 加载串口配置
        const serialResponse = await axios.get(`/api/config/serial/${deviceImei.value}`, { headers })
        Object.assign(serialConfig, serialResponse.data)
        
        // 加载网络配置
        const networkResponse = await axios.get(`/api/config/network/${deviceImei.value}`, { headers })
        Object.assign(networkConfig, networkResponse.data)
        
      } catch (error) {
        ElMessage.error('加载配置失败')
      } finally {
        loading.value = false
      }
    }
    
    const loadSubDevices = async () => {
      try {
        subDeviceLoading.value = true
        const token = sessionStorage.getItem('token')
        const response = await axios.get(`/api/sub-devices/main/${deviceImei.value}`, {
          headers: { Authorization: `Bearer ${token}` }
        })
        
        if (response.data.success) {
          subDevices.value = response.data.data
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        ElMessage.error('加载分设备列表失败')
      } finally {
        subDeviceLoading.value = false
      }
    }
    
    const handleSave = async () => {
      try {
        loading.value = true
        const token = sessionStorage.getItem('token')
        const headers = { Authorization: `Bearer ${token}` }
        
        // 保存当前激活的配置
        //if (activeTab.value === 'serial') {
        //  await axios.post(`/api/config/serial/${deviceImei.value}`, serialConfig, { headers })
        //} else if (activeTab.value === 'polling') {
        //  await axios.post(`/api/config/polling/${deviceImei.value}`, pollingConfig, { headers })
        //} else if (activeTab.value === 'network') {
        //  await axios.post(`/api/config/network/${deviceImei.value}`, networkConfig, { headers })
        //}
        const totalConfig = reactive({
                  serialConfig: serialConfig,
                  networkConfig: networkConfig
                })
        console.log(totalConfig);
        await axios.post(`/api/config/totalConfig/${deviceImei.value}`, totalConfig, { headers })
        
        ElMessage.success('配置保存成功')
      } catch (error) {
        ElMessage.error('配置保存失败')
      } finally {
        loading.value = false
      }
    }
    
    const goToSubDevices = () => {
      router.push(`/sub-devices/${deviceImei.value}`)
    }
    
    const viewKeys = (subDevice) => {
      router.push(`/device-keys/${subDevice.id}`)
    }
    
    const handleAddSubDevice = () => {
      router.push(`/sub-devices/${deviceImei.value}/add`)
    }
    
    const editSubDevice = (subDevice) => {
      router.push(`/sub-devices/edit/${subDevice.id}`)
    }
    
    const deleteSubDevice = async (subDevice) => {
      try {
        await ElMessageBox.confirm('确定要删除这个二级设备吗？', '警告', {
          type: 'warning'
        })
        
        const token = sessionStorage.getItem('token')
        const response = await axios.delete(`/api/sub-devices/${subDevice.id}`, {
          headers: { Authorization: `Bearer ${token}` }
        })
        
        if (response.data.success) {
          ElMessage.success('删除成功')
          loadSubDevices()
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }
    
    const handleSubDeviceSelectionChange = (selection) => {
      selectedSubDevices.value = selection
    }
    
    const handleBatchDeleteSubDevices = async () => {
      if (selectedSubDevices.value.length === 0) {
        ElMessage.warning('请选择要删除的二级设备')
        return
      }
      
      try {
        await ElMessageBox.confirm(`确定要删除选中的 ${selectedSubDevices.value.length} 个二级设备吗？`, '警告', {
          type: 'warning'
        })
        
        const token = sessionStorage.getItem('token')
        const ids = selectedSubDevices.value.map(item => item.id)
        const response = await axios.delete('/api/sub-devices/batch', {
          headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
          data: ids
        })
        
        if (response.data.success) {
          ElMessage.success('批量删除成功')
          loadSubDevices()
        } else {
          ElMessage.error(response.data.message)
        }
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('批量删除失败')
        }
      }
    }
    
    const formatTime = (timestamp) => {
      if (!timestamp) return ''
      const date = new Date(timestamp)
      return date.toLocaleString('zh-CN')
    }
    
    const handleLogout = () => {
      sessionStorage.removeItem('token')
      sessionStorage.removeItem('username')
      router.push('/login')
    }
    
    onMounted(() => {
      loadConfigs()
      loadSubDevices()
    })
    
    return {
      loading,
      username,
      deviceImei,
      activeTab,
      serialConfig,
      networkConfig,
      subDevices,
      subDeviceLoading,
      selectedSubDevices,
      handleSave,
      handleLogout,
      goToSubDevices,
      viewKeys,
      handleAddSubDevice,
      editSubDevice,
      deleteSubDevice,
      handleSubDeviceSelectionChange,
      handleBatchDeleteSubDevices,
      formatTime
    }
  }
}
</script> 